package org.dragonnova.business.web;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.dragonnova.business.model.Region;
import org.dragonnova.business.service.RegionService;
import org.dragonnova.business.service.TagService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.base.pub.util.DateUtils;

/**
 * 用户区域
 */
@Controller
@RequestMapping("/region")
public class RegionController extends BaseController {
	@Autowired
	private RegionService regionService;
	@Autowired
	private TagService tagService;

	/**
	 * 删除
	 */
	@RequestMapping("/delRegion")
	@ResponseBody
	public Map<String, Object> delRegion(HttpSession session, @RequestParam(value = "id", required = true) Integer id) {
		Integer uId = getUserId(session, true);
		try {
			boolean isUsed = tagService.isUsedZoneId(id);
			if (!isUsed) {
				return packDelInfo(regionService.delRegionById(id, uId));
			} else {
				return packInfo(false,"该区域正被使用！删除");
			}
		} catch (Exception e) {
			e.printStackTrace();
			return warnException(e);
		}

	}

	/**
	 * 保存
	 */
	@RequestMapping("/addRegion")
	@ResponseBody
	public Map<String, Object> addRegion(HttpSession session, Region region, String password) {
		try {
			Integer uId = getUserId(session, false);
			boolean isUsedName = regionService.isUsedName(uId, region.getName());
			if (isUsedName) {
				return packInfo(false,"该区域已存在！保存");
			}
			region.setSign("0");
			region.setUid(uId);
			return packDelInfo(regionService.addRegion(region));
		} catch (Exception e) {
			e.printStackTrace();
			return warnException(e);
		}
	}

	/**
	 * 更新
	 */
	@RequestMapping("/updateRegion")
	@ResponseBody
	public Map<String, Object> updateRegion(HttpSession session, Region region, String password) {
		Integer uId = getUserId(session, true);
		region.setUpdatetime(DateUtils.getTimes(new Date(), "yyyy-MM-dd HH:mm:ss"));
		region.setUid(uId);
		try {
			return packSaveInfo(regionService.updateRegion(region));
		} catch (Exception e) {
			e.printStackTrace();
			return warnException(e);
		}
	}

	/**
	 * 查询 管理员返回所有区域
	 */
	@RequestMapping("/findRegion")
	@ResponseBody
	public Map<String, Object> findRegion(HttpSession session, String searchText, Integer id) {
		Integer uId = getUserId(session, true);
		List<Region> list = new ArrayList<>();
		try {
			list = regionService.findRegion(uId, searchText, id);
		} catch (Exception e) {
			e.printStackTrace();
			return warnException(e);
		}
		Map<String, Object> map = new HashMap<>();
		map.put("result", 0);
		map.put("data", list);
		map.put("count", list.size());
		map.put("message", "查询成功！");
		return map;
	}
}
